package pl.edu.agh.xls2html;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import pl.edu.agh.xls2html.htmlelements.Document;
import pl.edu.agh.xls2html.htmlelements.HTMLHelper;

public class XLS2HTML {

	private static String defaultStyle = "input{\n" + "\tborder: none;\n"
			+ "\tbackground-color: inherit;\n" + "}\n" + "td{\n"
			+ "\t overflow: hidden" + "}\n" + "td div{\n"
			+ "\t overflow: hidden" + "}\n";

	public XLS2HTML() {

	}

	public static void main(String[] args) {
		if (args.length < 2) {
			String errorMsg = "Usage: XLS2HTML <input_file_name.xls> <output_folder_name> [options -s: static mode ]";
			error(errorMsg);
		}

		String input = args[0];
		String output = args[1];

		File out = new File(output);
		File in = new File(input);

		if (!in.exists())
			error("Can't find input file");

		if (!out.exists() && !out.mkdir())
			error("Can't create output folder");
		else if (!out.isDirectory())
			error("Can't create output folder");

		boolean staticMode = false;
		if (args.length == 3)
			if (args[2].equals("-s"))
				staticMode = true;

		XLS2HTML xls2html = new XLS2HTML();
		try {
			xls2html.convert(input, output, staticMode);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private static void error(String errorMsg) {
		System.out.println(errorMsg);
		System.exit(0);
	}

	private void convert(String input, String output, boolean staticMode)
			throws IOException {
		FileInputStream fis = new FileInputStream(input);
		HSSFWorkbook hwb = new HSSFWorkbook(fis);

		Document doc = new Document(hwb);
		if (staticMode)
			doc.setStaticMode();

		int sn = doc.getSheetsNumber();
		for (int i = 0; i < sn; i++) {
			String html = doc.getSheetHTML(i);
			String css = doc.getSheetCSS(i);

			String htmlFileName = output + "/sheet" + i + ".html";
			writeFile(htmlFileName, html);

			String cssFileName = output + "/cells" + i + ".css";
			writeFile(cssFileName, css);
		}

		String formulaFileName = output + "/formula.js";
		String formulaFileContent = doc.getJSResource("resource/formula.js");
		writeFile(formulaFileName, formulaFileContent);

		String cssFileName = output + "/style.css";
		writeFile(cssFileName, defaultStyle);

		String menuFileName = output + "/menu.html";
		String menuHtmlContent = doc.getMenuHTML();
		writeFile(menuFileName, menuHtmlContent);

		String indexFileName = output + "/index.html";
		String indexFileContent = HTMLHelper.makeFrameset();
		writeFile(indexFileName, indexFileContent);

		System.out.println("Completed successfully!");
	}

	private void writeFile(String fullFileName, String fileContent)
			throws IOException {
		FileWriter fileWriter = new FileWriter(fullFileName);
		fileWriter.write(fileContent);
		fileWriter.close();
	}

}
